package com.rainripple.java.common.mapper;

import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;

import com.rainripple.java.common.log.Log;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreeMarkerMapperBuilder implements IMapperBuilder {
	public static final String MAPPER_TEMPLATE_NAME = "SqlMapper.ftl";
	private Template template;

	@Override
	public byte[] build(EntityInfo entityInfo) {
		if (null == entityInfo) {
			return null;
		}
		if (null == template) {
			initFreemarker();
		}
		return doBuild(entityInfo);
	}

	private void initFreemarker() {
		Configuration freemarkerCfg = new Configuration();
		freemarkerCfg.setClassForTemplateLoading(this.getClass(), "");
		freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
		try {
			template = freemarkerCfg.getTemplate(MAPPER_TEMPLATE_NAME);
		} catch (IOException e) {
			Log.debug(e.toString());
		}
	}

	private byte[] doBuild(EntityInfo map) {
		template.setEncoding("UTF-8");
		StringWriter writer = new StringWriter();
		try {
			template.process(map, writer);
			writer.close();
			return writer.toString().getBytes("UTF-8");
		} catch (TemplateException e) {
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}
		return null;
	}

}
